//
//  ElectronContractViewController.m
//  阿帕
//
//  Created 阿帕 on 2020/1/4.
//  Copyright © 2020 GCY. All rights reserved.
//

#import "ElectronContractViewController.h"

#import "ElectronDetailViewController.h"

#import "ContractCell.h"

#import <QuickLook/QuickLook.h>

@interface ElectronContractViewController ()<UITableViewDataSource, UITableViewDelegate ,CYNormalAlertViewEventDelegate>

@property (strong , nonatomic)UITextField *textFiled;

@property (strong , nonatomic)UITableView *tableView;

@property (strong , nonatomic)NSMutableArray *dataArray;

@property (strong , nonatomic)UIImageView *foundImageView;

@property (nonatomic, assign) NSInteger pageNum;

@end

@implementation ElectronContractViewController

static const CGFloat cellHeight = 170 + 40 + 45;

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _pageNum = 1;
    
    [self setupBaseView];
    
}

- (void)setupBaseView {
    
    self.navigationItem.title = @"合同列表";

    self.view.backgroundColor = BackgroundColor;
    
    _textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 10, ScreenW, 40)];
    _textFiled.font = font(14);
    _textFiled.text = @"";
    _textFiled.backgroundColor = [UIColor whiteColor];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    _textFiled.keyboardType = UIKeyboardTypeDefault;
    _textFiled.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请填写查询条件" attributes:@{NSForegroundColorAttributeName: Light_TextColor}];
    _textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 15, 40)];
    _textFiled.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 15, 40)];
    _textFiled.leftViewMode = UITextFieldViewModeAlways;
    [_textFiled addSubview: leftView];
    
    
    UIImageView *searchImage = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenW-40, 10, 20, 20)];
    searchImage.userInteractionEnabled = YES;
    searchImage.image = [UIImage imageNamed:@"gcy_icon_search_siji"];
    _textFiled.rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    _textFiled.rightViewMode = UITextFieldViewModeAlways;
    [_textFiled addSubview:searchImage];
    
    [searchImage nyl_addTapGes:^{
        _pageNum = 1;
        [self contractListRequest];
    }];
    
    [self.view addSubview:_textFiled];
    
    [self.view addSubview:self.tableView];

    [self contractListRequest];
}

- (void)contractListRequest {
    WEAKSELF
    
    if (_pageNum == 1) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *params = @{
        @"pageSize":DEFULT_LOAD_NUM,
        @"pageNum":[NSNumber numberWithInteger:_pageNum],
        @"contractType":@"0",//合同类型，0承运，1托运
        @"searchInfo": _textFiled.text,
        @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
    };
    
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], ORDERDETAILCONTRACT) withParameter:params withVC:self netName:@"电子合同列表" success:^(id response, NSString *msg) {
        
        if ([response[@"records"] count] != 0) {
            [weakSelf.dataArray addObjectsFromArray:[ContractRecordModel mj_objectArrayWithKeyValuesArray:response[@"records"]]];
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            
            weakSelf.foundImageView.hidden = YES;
            weakSelf.tableView.hidden = NO;
            
        } else{
            if (_pageNum == 1) {
                weakSelf.foundImageView.hidden = NO;
                weakSelf.tableView.hidden = YES;
            }
            
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            
        }
        
        [weakSelf.tableView reloadData];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

//上拉刷新数据
- (void)loadNewData{
    _pageNum = 1;
    [self contractListRequest];
}
- (void)loadMoreData{
    _pageNum ++;
    [self contractListRequest];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ContractCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellID"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    ContractRecordModel *model = self.dataArray[indexPath.row];
    cell.model = model; //[self.dataArray objectAtIndex:indexPath.row];
    
    WEAKSELF
    cell.blockElectSign = ^(id anyObject) {
        [weakSelf btnElectSiginAction:model];
    };
    return cell;
    
}



#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ContractRecordModel *model = self.dataArray[indexPath.row];
    if ([DCSpeedy isBlankString:model.contractPath] == YES) {
        [XSInfoView showInfo:@"暂无合同" onView:self.view];
        return;
    }
    ElectronDetailViewController *edvc = [[ElectronDetailViewController alloc] init];
    edvc.contractPath = model.contractPath;
    edvc.pageTitle = @"合同详情";
    [self.navigationController pushViewController:edvc animated:YES];
    
}


#pragma mark ----------btnAction

- (void)btnElectSiginAction:(ContractRecordModel *)model{
    

    WEAKSELF
    
//    0非短信 1短信验证
    if (![[UserDefaultUtil valueForKey:Login_Branch][@"elecSignType"] isEqual:@"1"]) {
        
        [[ElectSignViewAlert shared]initWithContent:@"确定生成电子签章吗?" ClickOnSure:^(NSString * _Nonnull strSure) {
            DebugLog(@"电子签章");
            [weakSelf getElecSignTypeWithOrderCode:model.code];
        } ClickOnCancle:^(NSString * _Nonnull strCancle) {

        }];
        [[ElectSignViewAlert shared] show];
        
    }else{
         [self getElecSignTypeWithAouthCodeModel:model];
    }
    
    

    
   
}
#pragma mark ----------短信验证

- (void)getElecSignTypeWithAouthCodeModel:(ContractRecordModel *)model{
    
    
    NSArray *listTitle = @[@"货源单号",@"运单编号",@"手机号",@"验证码："];
    
    NSArray *listContent = @[model.mainOrderNumber,model.orderCode,model.driverPhone,model.code];

    WEAKSELF
    ElectSignListViewAlert *alert = [ElectSignListViewAlert shared];
    [alert initWithTitle:@"电子签章验证码" listTitle:listTitle listContent:listContent ClickOnSure:^(NSString * _Nonnull strSure) {
        [weakSelf.tableView.mj_header beginRefreshing];
    } ClickOnCancle:^(NSString * _Nonnull strCancle) {
        
    }];
    [alert show];
//    WS(ws);
//    CJAlertViewSign *alert = [[CJAlertViewSign alloc]initWithTitle:@"电子签章验证码" listTitle:listTitle listContent:listContent ClickOnSure:^(NSString * _Nonnull strSure) {
//        [ws.tableView.mj_header beginRefreshing];
//    } ClickOnCancle:^(NSString * _Nonnull strCancle) {
//
//    }];
//
//    alert.center=self.view.center;
//    WLAlertView * alertView = [[WLAlertView alloc]init];
//    alertView.containerView = alert;
//    alertView.isTouchOtherUndissmiss = YES;
//    [alertView show];

    
}





/// 直接生成
/// @param strCode <#strCode description#>
- (void)getElecSignTypeWithOrderCode:(NSString *)strCode{
    
//    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tps-api/elecSign/%@",CJBaseUrl,strCode);
    WEAKSELF
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/elecSign/%@",[NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl],strCode) withParameter:@{ @"token":[UserDefaultUtil valueForKey:USER_TOKEN],} withVC:self netName:@"电子签章不通过短信" success:^(id response, NSString *msg) {
        
        [XSInfoView showInfo:msg onView:weakSelf.view];
        
        [weakSelf.tableView.mj_header beginRefreshing];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];

}


#pragma mark - LazyLoad
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.frame = CGRectMake(0, 60, ScreenW, ScreenH - NavHeight - 60);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        //注册单元格
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ContractCell class]) bundle:nil] forCellReuseIdentifier:@"CellID"];
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    }
    
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (UIImageView *)foundImageView {
    if (!_foundImageView) {
        _foundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 170, 170)];
        _foundImageView.image = image(@"gcy_img_list_found");
        _foundImageView.contentMode = UIViewContentModeScaleAspectFit;
        _foundImageView.center = self.view.center;
        _foundImageView.cy_centerY -=50;
        [self.view addSubview:_foundImageView];
    }
    return _foundImageView;
}

@end
